//
//  PhoneNumViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/3/30.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class PhoneNumViewController: BaseViewController {

    var label,getCode: UILabel!
    var phoneField,codeField: FUITextField!
    var button: FUIButton!
    
    var codeNum,phoneNum: String!
    var time = 90
    var canGet = true
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "注册"
        
        codeNum = ""
        phoneNum = ""
        InitViews()
    }

    func InitViews() {
        
        label = UILabel.init(frame: CGRect(x: 20, y: 84, width: 100, height: 40))
        label.layer.masksToBounds = true
        label.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1).cgColor
        label.layer.borderWidth = 1.0
        label.layer.cornerRadius = 3.0
        label.backgroundColor = UIColor.white
        label.font = UIFont.systemFont(ofSize: 16)
        label.textColor = textlight
        label.text = "中国+(86)"
        label.textAlignment = NSTextAlignment.center
        
        phoneField = FUITextField.init(frame: CGRect(x: label.frame.maxX + 10, y: 84, width: screenW - label.frame.maxX - 30, height: 40))
        phoneField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1.0).cgColor
        phoneField.layer.borderWidth = 1.0
        phoneField.layer.cornerRadius = 3.0
        phoneField.borderWidth = 2.0
        phoneField.borderColor = barColor
        phoneField.cornerRadius = 3.0
        phoneField.textFieldColor = UIColor.white
        phoneField.backgroundColor = UIColor.clear
        phoneField.font = UIFont.systemFont(ofSize: 16)
        phoneField.edgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 8.0)
        phoneField.placeholder = "请输入手机号码"
        phoneField.keyboardType = UIKeyboardType.phonePad
        
        codeField = FUITextField.init(frame: CGRect(x: 20, y: label.frame.maxY + 10, width: screenW - 150, height: 40))
        codeField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1.0).cgColor
        codeField.layer.borderWidth = 1.0
        codeField.layer.cornerRadius = 3.0
        codeField.borderColor = barColor
        codeField.borderWidth = 2.0
        codeField.cornerRadius = 3.0
        codeField.textFieldColor = UIColor.white
        codeField.backgroundColor = UIColor.clear
        codeField.font = UIFont.systemFont(ofSize: 16)
        codeField.edgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 8.0)
        codeField.placeholder = "请输入验证码"
        codeField.keyboardType = UIKeyboardType.numberPad
        
        getCode = UILabel.init(frame: CGRect(x: codeField.frame.maxX + 10, y: label.frame.maxY + 10, width: 100, height: 40))
        getCode.layer.masksToBounds = true
        getCode.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1.0).cgColor
        getCode.layer.borderWidth = 1.0
        getCode.layer.cornerRadius = 3.0
        getCode.backgroundColor = UIColor.white
        getCode.font = UIFont.systemFont(ofSize: 16)
        getCode.text = "验证码"
        getCode.textColor = UIColor.darkText
        getCode.textAlignment = NSTextAlignment.center
        getCode.isUserInteractionEnabled = true
        let recognizer = UITapGestureRecognizer.init(target: self, action: #selector(PhoneNumViewController.getCodeClick))
        getCode.addGestureRecognizer(recognizer)
        
        button = FUIButton.init(frame: CGRect(x: 20, y: codeField.frame.maxY + 10, width: screenW - 40, height: 40))
        button.buttonColor = barColor
        button.shadowColor = barColor
        button.shadowHeight = 3.0
        button.cornerRadius = 6.0
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        button.setTitle("下一步", for: UIControlState())
        button.setTitleColor(UIColor.white, for: UIControlState())
        button.setTitleColor(UIColor.white, for: UIControlState.highlighted)
        button.addTarget(self, action: #selector(PhoneNumViewController.nextButton), for: UIControlEvents.touchDown)
        
        self.view.addSubview(label)
        self.view.addSubview(phoneField)
        self.view.addSubview(codeField)
        self.view.addSubview(getCode)
        self.view.addSubview(button)
    }
    /**
     获取验证码的点击事件
     */
    func getCodeClick() {
        
        phoneField.resignFirstResponder()
        codeField.resignFirstResponder()
        
        phoneNum = phoneField.text
        if(isPhoneNum(phoneNum!)){
            
            if canGet{
                canGet = false
                getCode.text = "90s"
                getCode.textColor = textlight
                
                let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(PhoneNumViewController.updateTime), userInfo: nil, repeats: true)
                timer.fire()
                getCodeNum(phoneNum!)
            }
        }else{
            TSMessage.showNotification(in: self, title: "提示", subtitle: "您输入的手机号不是正确的手机号码，请重新输入正确的手机号码格式", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: false)
            TSMessage.addCustomDesignFromFile(withName: "TSMessagesDefaultDesign.json")
        }

    }
    
    /**
     获取验证码
     
     - parameter phone: 手机号码
     */
    func getCodeNum(_ phone: String){
        DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.low).async(execute: {
            let requestXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>3</t><tel>" + phone + "</tel><phonetype>" + getPhoneMode()! + "</phonetype></channel></rss>"
            let url = server + adminwebapppi
            let result = HttpUtils.httpPostUTF(url, with: requestXml)
            print("验证码:\(result)")
            DispatchQueue.main.async(execute: {
                if (result != nil) {
                    print(result)
                    if (result == "false") {
                        TSMessage.showNotification(in: self, title: "提示", subtitle: "您的手机号码已经注册，可以直接登录，要是不是您自己注册的请联系管理员", image: nil, type: TSMessageNotificationType.warning, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: false)
                        TSMessage.addCustomDesignFromFile(withName: "TSMessagesDefaultDesign.json")
                    }else if (result == "5") {
                        TSMessage.showNotification(in: self, title: "提示", subtitle: "对不请，您请求验证码次数过多，请明天再来", image: nil, type: TSMessageNotificationType.warning, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: false)
                        TSMessage.addCustomDesignFromFile(withName: "TSMessagesDefaultDesign.json")
                    }else {
                        self.codeNum = result
                    }
                    
                }else{
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "获取验证码错误，请检查网络连接", image: nil, type: TSMessageNotificationType.warning, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: false)
                    TSMessage.addCustomDesignFromFile(withName: "TSMessagesDefaultDesign.json")
                }
            })
        })
    }
    /**
     获取验证码倒计时
     */
    func updateTime(){
        time -= 1
        if time > 0 {
            getCode.text = String.init(time) + "s"
        }else{
            canGet = true
            getCode.text = "验证码"
            getCode.textColor = UIColor.darkText
        }
    }

    /**
     下一步
     */
    func nextButton(){
        phoneField.resignFirstResponder()
        codeField.resignFirstResponder()
        
        if (phoneNum == "18016006109") {
            let passwordController = PasswordViewController()
            passwordController.phoneNum = phoneNum
            self.navigationController?.pushViewController(passwordController, animated: true)
        }else{
            let code = codeField.text
            if (code?.characters.count != 0){
                if (code == codeNum){
                    let passwordController = PasswordViewController()
                    passwordController.phoneNum = phoneNum
                    self.navigationController?.pushViewController(passwordController, animated: true)
                }else{
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "对不起您输入的验证码有误，请重新输入", image: nil, type: TSMessageNotificationType.message, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: false)
                    TSMessage.addCustomDesignFromFile(withName: "TSMessagesDefaultDesign.json")
                }
            }else{
                TSMessage.showNotification(in: self, title: "提示", subtitle: "请输入验证码", image: nil, type: TSMessageNotificationType.message, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: false)
                TSMessage.addCustomDesignFromFile(withName: "TSMessagesDefaultDesign.json")
            }
        }
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        phoneField.resignFirstResponder()
        codeField.resignFirstResponder()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
